package com.example.patients;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.patients.adapter.Adapter;
import com.example.patients.database.DbPatients;
import com.example.patients.entity.PatientsBean;

import java.util.ArrayList;
import java.util.List;

public class QueryPatientsActivity extends AppCompatActivity implements View.OnClickListener {
    ListView QueryLv;//列表
    EditText EtNumber, EtName;//输入框病床号和姓名
    List<PatientsBean> mData;//数据源
    Adapter adapter;//适配器对象
    DbPatients dbPatients;//数据库

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query_patients);//绑定所有事件
        QueryLv = findViewById(R.id.query_lv);
        EtName = findViewById(R.id.et_name);
        EtNumber = findViewById(R.id.et_number);
        mData = new ArrayList<>();
        adapter = new Adapter(this, mData);
        QueryLv.setAdapter(adapter);
        dbPatients = new DbPatients(this);

    }

    /**
     * 按钮点击事件
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            Intent intent = new Intent(QueryPatientsActivity.this, MainActivity.class);
            //实现页面跳转
            startActivity(intent);
            finish();
        } else if (id == R.id.iv_query) {
            String number = EtNumber.getText().toString().trim();
            String name = EtName.getText().toString().trim();
            if (TextUtils.isEmpty(number) && TextUtils.isEmpty(name)) {
                Toast.makeText(this, "请输入病床号或姓名！", Toast.LENGTH_SHORT).show();
            } else if (!TextUtils.isEmpty(number) && !TextUtils.isEmpty(name)) {
                //开始以病床号和姓名搜索
                List<PatientsBean> list = DbPatients.getPatientListByNumberAndName(number, name);
                mData.clear();//将原来搜索的消息清除
                mData.addAll(list);//显示在列表上
                adapter.notifyDataSetChanged();//实时更新
            } else if (TextUtils.isEmpty(number)) {
                //开始以姓名搜索
                List<PatientsBean> list = DbPatients.getPatientListByName(name);
                mData.clear();//将原来搜索的消息清除
                mData.addAll(list);//显示在列表上
                adapter.notifyDataSetChanged();//实时更新
            } else if (TextUtils.isEmpty(name)) {
                List<PatientsBean> list = DbPatients.getPatientListByNumber(number);
                mData.clear();//将原来搜索的消息清除
                mData.addAll(list);//显示在列表上
                adapter.notifyDataSetChanged();//实时更新
//                }
            }
        }
    }
}
